package com.train.classeval.controller;


import com.train.classeval.entity.AddRoleRequest;
import com.train.classeval.entity.Role;
import com.train.classeval.service.IRoleService;
import com.train.classeval.service.impl.RoleServiceImpl;
import com.train.classeval.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xs
 * @since 2021-10-08
 */
@RestController
public class RoleController {

    @Autowired
    private IRoleService roleService;

    /**
     * 查询所有角色
     * @return
     */
    @GetMapping("/showRole")
    public JsonData showRole() {
        List<Role> list = roleService.list();
        if (list != null) {
            return JsonData.BuildSuccess(list, "查询角色成功！");
        }
        return JsonData.BuildError("查询失败！");
    }

    /**
     * 添加角色接口
     * @param role
     * @return
     */
    @PostMapping("/additionRole")
    public JsonData additionRole(@RequestBody Role role) {
        role.setCreateDate(new Date());
        role.setUpdateDate(new Date());
        role.setStatus(0);
        boolean save = roleService.save(role);
        if (save == true) {
            return JsonData.BuildSuccess("添加角色成功！");
        }
        return JsonData.BuildError("添加角色失败！");
    }

    /**
     * 删除权限接口
     * @param rid
     * @return
     */
    @DeleteMapping("/deleteRole/{rid}")
    public JsonData deleteRole(@PathVariable("rid") Integer rid) {
        boolean d = roleService.removeById(rid);
        if (d == true) {
            return JsonData.BuildSuccess("删除角色成功！");
        }
        return JsonData.BuildError("删除角色失败！");
    }

    /**
     * 为用户添加角色的控制器
     * @param addRoleRequest
     * @return
     */
    @PostMapping("/addRole")
    public JsonData addRole(@RequestBody AddRoleRequest addRoleRequest) {
        final int count = roleService.selectUserRole(addRoleRequest.getUid(), addRoleRequest.getRid());
        //当前用户有当前角色了
        if (count == 0) {
            final int i = roleService.addRole(addRoleRequest.getUid(), addRoleRequest.getRid());
            if (i == 1) {
                return JsonData.BuildSuccess("分配角色成功!");
            }
        }else {
            return JsonData.BuildError("当前用户有当前权限了!");
        }
        return JsonData.BuildError("分配角色失败");
    }
}
